package steed.util.system;

import java.io.File;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

import steed.exception.runtime.system.FrameworkException;
import steed.util.base.BaseUtil;
import steed.util.base.PathUtil;

public class TaskUtil {
	private final static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(50);
	public static Scheduler scheduler;
	
	
	private void startTask(Element element){
		String attributeValue = element.attributeValue("class");
		try {
			
			
			JobKey jobKey = new JobKey(attributeValue);
			TriggerKey triggerKey = new TriggerKey(attributeValue+"_Trigger");
			Trigger trigger = TriggerBuilder.newTrigger()
					.withIdentity(attributeValue+"_Trigger")
					.withSchedule(CronScheduleBuilder.cronSchedule(element.attributeValue("cron")))
					.forJob(jobKey)
					.build();
			if(scheduler.checkExists(jobKey)) {
				if ("true".equals(element.attributeValue("delete"))) {
					scheduler.deleteJob(jobKey);
					BaseUtil.getLogger().info("移除定时任务{}!",attributeValue);
					return;
				}else if ("true".equals(element.attributeValue("refreshOnStartUp"))) {
					scheduler.rescheduleJob(triggerKey, trigger);
					BaseUtil.getLogger().info("刷新定时任务{} cron表达式!",attributeValue);
				}
				return;
			}
			if ("true".equals(element.attributeValue("delete"))) {
				return;
			}
			
			JobDetail job = JobBuilder.newJob((Class<? extends Job>) Class.forName(attributeValue))
	                .withIdentity(attributeValue)
	                .build();

			scheduler.checkExists(triggerKey);
	            // Trigger the job to run now, and then repeat every 40 seconds

	            // Tell quartz to schedule the job using our trigger
            scheduler.scheduleJob(job, trigger);
            
            BaseUtil.getLogger().info("定时任务{}添加成功!",attributeValue);
		} catch (Exception e) {
			BaseUtil.getLogger().error("启动定时任务"+attributeValue+"失败!",e);
		}
	}
	
	public static ScheduledExecutorService getScheduledexecutorservice() {
		return scheduledExecutorService;
	}

	@SuppressWarnings("unchecked")
	public void init(){
		try {
            // Grab the Scheduler instance from the Factory
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            // and start it off
            scheduler.start();
            try {
            	Document doc = new SAXReader().read(new File(PathUtil.getFormalClassesPath()+"properties/task.xml"));
            	Element root = doc.getRootElement();
            	List<Element> elements = root.elements("task");
            	for (Element temp:elements) {
            		startTask(temp);
            	}
            } catch (DocumentException e) {
            	throw new FrameworkException("task.xml解析失败!", e);
            }

        } catch (SchedulerException se) {
            throw new FrameworkException("quartz初始化失败!", se);
        }
		
		
	}
}
